package com.up.jiasai.interceptors;
import com.up.vms.application.base.abs.BaseHandlerInterceptor;
import com.up.vms.application.base.utils.RequestUtils;
import com.up.jiasai.modules.oauth.jwt.JwtTokenUtil;

import com.up.vms.infrastructure.util.CommonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户登录拦截器
 * 功能说明：<br>
 * 模块名称：NRAdmin<br>
 * 功能描述：AdminLoginInterceptor<br>
 * 文件名称: AdminLoginInterceptor.java<br>
 * 系统名称：ICELOVE<br>
 * 软件著作权：ICELOVE 版权所有<br>
 * 开发人员：lujun <br>
 * 开发时间：2016-10-11 下午8:40:45<br>
 * 系统版本：1.0.0<br>
 */
public class UserLoginInterceptor extends BaseHandlerInterceptor{
	private static final Logger logger = LoggerFactory.getLogger(UserLoginInterceptor.class);
	private String signKey = "3c842a4841c651dd941b37e7b440f903";//不能注入,对象是new 出来的

	@Override
	public boolean preHandle(HttpServletRequest request,HttpServletResponse response,Object handler) throws Exception{
		super.init(request,response,handler);
		RequestUtils.printRequestHeader(request);
		String reqUrl = request.getServletPath();
		String header = request.getHeader("Authorization");
		if ("OPTIONS".equals(request.getMethod())) {
			response.setStatus(HttpServletResponse.SC_OK);
			return true;
		}
		try{
			//logger.error("解析授权信息>>>> "+header);
			if (CommonUtils.isNotNull(header)) {
				String openId = new JwtTokenUtil(signKey).getUserFromToken(header);
				//绑定传递到当前请求里面
				request.setAttribute("openId", openId);
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("授权失败: <"+reqUrl+"> "+e.getMessage());
		}
		return true;
	}
	@Override
	public void postHandle(HttpServletRequest request,HttpServletResponse response,Object handler,ModelAndView modelAndView) throws Exception{
		//logger.info("<postHandle>");
	}

	@Override
	public void afterCompletion(HttpServletRequest request,HttpServletResponse response,Object handler,Exception ex) throws Exception{
		//logger.info("<afterCompletion>"+handler.getClass().getName());
	}
}
